package com.caldremch.androidfoundation.http;


import android.text.TextUtils;
import android.util.Log;

import com.caldremch.androidfoundation.http.interceptor.HeadersInterceptor;
import com.caldremch.androidfoundation.http.model.HttpCode;
import com.caldremch.androidfoundation.utils.EncodeUtils;
import com.caldremch.androidfoundation.utils.MyHttpUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import es.dmoral.toasty.Toasty;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.HttpException;
import retrofit2.Retrofit;

/**
 * @author Caldremch
 * @date 2018/11/6
 * @Email caldremch@163.com
 * @describe 星火 网络请求工具
 **/
public class XHttpManager {


    public static void login(String userName, String password) {

        String encode = new String(EncodeUtils.base64Encode(userName + ":" + password));
        Map<String, String> map = new HashMap<>();
        map.put("Authorization", "Basic " + encode);

        OkHttpClient.Builder builder = RetrofitHelper.getOkHttpBuilder();
        builder.addInterceptor(new HeadersInterceptor(map));
        Retrofit retrofit = RetrofitHelper.getRetrofit(builder);
        ApiService apiService = retrofit.create(ApiService.class);

        apiService.login().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {

                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Log.d("caldremch", "onNext");

                        try {
                            String x = responseBody.string();
                            Log.d("caldremch", "onNext = " + x);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        handleError(e);
                    }

                    @Override
                    public void onComplete() {
                        Log.d("caldremch", "onComplete");

                    }
                });


    }

    private static void handleError(Throwable throwable) {
        try {
            HttpException exception = (HttpException) throwable;
            ResponseBody body = exception.response().errorBody();
            String bodyStr =  body.string();
            String errorMsg = EncodeUtils.unicodeToString(bodyStr);
            Log.d("caldremch", "errorBody => " + errorMsg);
            handleTips(exception.code(), errorMsg);
//            exception.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void handleTips(int code, String msg) {
        switch (code) {
            case HttpCode.BAD_REQUEST:
                Toasty.normal(MyHttpUtils.getContext(), msg).show();
                break;
            case HttpCode.UNAUTHORIZED:

                String errorMsg = TextUtils.isDigitsOnly(msg) ? msg : "请重新登录";
                Toasty.normal(MyHttpUtils.getContext(), errorMsg).show();
                //todo 登出操作, 清楚用户数据, 跳转到登陆页面

                break;
            case HttpCode.BAD_GATEWAY:
            case HttpCode.INTERNAL_SERVER_ERROR:
                Toasty.normal(MyHttpUtils.getContext(), "加载失败").show();
                break;
            default:
                Toasty.normal(MyHttpUtils.getContext(), "加载失败").show();
                break;
        }
    }


}
